package com.vote.admin.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vote.common.entity.VoteUser;
import com.vote.common.enums.UserSessionEnum;
import com.vote.common.enums.UserTypeEnum;
import com.vote.common.returns.RespCode;
import com.vote.common.returns.RespEntity;
import com.vote.common.service.VoteUserService;
import com.vote.admin.vo.param.RegisterParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@Service
public class VoteUserRegisterService {

    @Autowired
    private VoteUserService voteUserService;

    /**
     * 生成验证码
     * @param response
     * @param session
     */
    public RespEntity createCode(HttpServletResponse response, HttpSession session){
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            captcha.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            log.error("生成验证码失败", e.getMessage());
        }
        session.setAttribute(UserSessionEnum.OLD_CODE.getCode(), captcha.getCode());
        return new RespEntity(RespCode.SUCCESS);
    }

    /**
     * 校验账号
     * @param username
     * @return
     */
    public RespEntity checkUsername(String username) {
        QueryWrapper<VoteUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(VoteUser::getUsername, username);
        VoteUser voteUser = voteUserService.getOne(queryWrapper);
        if (Objects.nonNull(voteUser)) {
            log.info("该账号已经存在, username={}", username);
            return new RespEntity(RespCode.EXIST);
        }
        return new RespEntity(RespCode.SUCCESS);
    }

    /**
     * 注册
     * @param registerParam
     * @return
     */
    public RespEntity register(RegisterParam registerParam, HttpSession session) {

        //校验验证码
        String oldCode = (String) session.getAttribute(UserSessionEnum.OLD_CODE.getCode());
        if (! registerParam.getCode().equals(oldCode)) {
            log.info("验证码输入不一致，oldCode={}, newCode={}", oldCode, registerParam.getCode());
            return new RespEntity(RespCode.CODE_ERROR);
        }

        //数据组装
        VoteUser voteUser = VoteUser.builder()
                .username(registerParam.getUsername())
                .password(registerParam.getPassword())
                .name(registerParam.getName())
                .type(UserTypeEnum.USER.getCode())
                .build();

        //添加用户表数据
        voteUserService.save(voteUser);

        return new RespEntity(RespCode.SUCCESS);
    }

}
